package cn.ac.jaas.isc.vegetable.quartz.util;

import cn.ac.jaas.isc.vegetable.common.data.tenant.TenantBroker;
import cn.ac.jaas.isc.vegetable.quartz.constants.VegetableQuartzEnum;
import cn.ac.jaas.isc.vegetable.quartz.entity.SysJob;
import cn.ac.jaas.isc.vegetable.quartz.entity.SysJobLog;
import cn.ac.jaas.isc.vegetable.quartz.event.SysJobLogEvent;
import cn.ac.jaas.isc.vegetable.quartz.service.SysJobService;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.quartz.CronTrigger;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;

import java.time.ZoneId;
import java.util.Date;

/**
 * @author 张高昌
 * @date 2022/4/30 16:23
 * @description: 定时任务反射工具类
 */
@Slf4j
@Aspect
@RequiredArgsConstructor
public class TaskInvokeUtil {

    private final ApplicationEventPublisher publisher;

    /**
     * 注意这里必须要用这个@Autowired，不要问为什么，我也不知道
     */
    @Autowired
    private SysJobService sysJobService;

    @SneakyThrows
    public void invokeMethod(SysJob sysJob, Trigger trigger) {

        // 执行开始时间
        long startTime;
        // 执行结束时间
        long endTime;
        // 获取执行开始时间
        startTime = System.currentTimeMillis();
        // 更新定时任务表内的状态、执行时间、上次执行时间、下次执行时间等信息
        SysJob updateSysop = new SysJob();
        updateSysop.setJobId(sysJob.getJobId());
        // 日志
        SysJobLog sysJobLog = new SysJobLog();
        sysJobLog.setJobId(sysJob.getJobId());
        sysJobLog.setJobName(sysJob.getJobName());
        sysJobLog.setJobGroup(sysJob.getJobGroup());
        sysJobLog.setJobOrder(sysJob.getJobOrder());
        sysJobLog.setJobType(sysJob.getJobType());
        sysJobLog.setExecutePath(sysJob.getExecutePath());
        sysJobLog.setClassName(sysJob.getClassName());
        sysJobLog.setMethodName(sysJob.getMethodName());
        sysJobLog.setMethodParamsValue(sysJob.getMethodParamsValue());
        sysJobLog.setCronExpression(sysJob.getCronExpression());
        sysJobLog.setTenantId(sysJob.getTenantId());
        try {
            // 执行任务
            ITaskInvoke iTaskInvoke = TaskInvokeFactory.getInvoker(sysJob.getJobType());
            // 确保租户上下文有值，使得当前线程中的多租户特性生效。
            TenantBroker.runAs(sysJob.getTenantId(), tenantId -> iTaskInvoke.invokeMethod(sysJob));

            // 记录成功状态
            sysJobLog.setJobMessage(VegetableQuartzEnum.JOB_LOG_STATUS_SUCCESS.getDescription());
            sysJobLog.setJobLogStatus(VegetableQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType());
            // 任务表信息更新
            updateSysop.setJobExecuteStatus(VegetableQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType());
        } catch (Throwable e) {
            log.error("定时任务执行失败，任务名称：{}；任务组名：{}，cron执行表达式：{}，执行时间：{}", sysJob.getJobName(), sysJob.getJobGroup(), sysJob.getCronExpression(), new Date());
            // 记录失败状态
            sysJobLog.setJobMessage(VegetableQuartzEnum.JOB_LOG_STATUS_FAIL.getDescription());
            sysJobLog.setJobLogStatus(VegetableQuartzEnum.JOB_LOG_STATUS_FAIL.getType());
            sysJobLog.setExceptionInfo(StrUtil.sub(e.getMessage(), 0, 2000));
            // 任务表信息更新
            updateSysop.setJobExecuteStatus(VegetableQuartzEnum.JOB_LOG_STATUS_FAIL.getType());
        } finally {
            // 记录执行时间 立刻执行使用的是simple Trigger
            if (trigger instanceof CronTrigger) {
                updateSysop.setStartTime(trigger.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                updateSysop.setPreviousTime(trigger.getPreviousFireTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                updateSysop.setNextTime(trigger.getNextFireTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
            }
            // 记录执行时长
            endTime = System.currentTimeMillis();
            sysJobLog.setExecuteTime(String.valueOf(endTime - startTime));

            publisher.publishEvent(new SysJobLogEvent(sysJobLog));
            sysJobService.updateById(updateSysop);
        }
    }

}
